import { director, sys } from "cc";
import { State, WSConnectedEvent, WSConnectingEvent, WSDisconnectEvent, WSRecvDataEvent } from "./NetCfg";

class WsMgr {

    private socket: any = null;
    private state: State = State.Invalid;
    url: any;

    constructor(){
        console.log('=========初始化数据==========')
        this.initWs();
    }   

    initWs(){
        this.state = State.Invalid;
        let platform = sys.platform;
        if(platform === sys.Platform.WECHAT_GAME){
            this.socket = window['wx'];
        }else{
        }
    }
    
    public connectServer(url: string){
        if(sys.platform === sys.Platform.WECHAT_GAME){
            console.log('==========微信平台==========');
            this._connectToServerWx(url);
        }else{
            console.log('==========web开发平台平台==========');
            this._connectToServer(url);
        }
    }

    //发送的二进制数据
    public SendData(buf){
        if(sys.platform === sys.Platform.WECHAT_GAME){
            this._sendDataWx(buf);
        }else{
            this._sendData(buf);
        }
    }

    //发送json 数据
    public sendJsonData(_type, _data){
        let jsonData = {
            type: _type,
            data: _data,
        }
        let msg = JSON.stringify(jsonData);

        if(sys.platform === sys.Platform.WECHAT_GAME){
            // this._sendDataWx(buf);
            this.socket.sendSocketMessage({
                data: msg,
                success: () => {
                    console.log('数据发送成功');
                },
                fail: (err) => {
                    console.log('数据发送失败：', err);
                }
            });
        }else{
            this.socket.send(msg);
        }
    }

    //web端链接服务
    private _connectToServer(url: string = null): void {
        console.log('=====ConnectToServer======',this.url,this.state)
        if(this.state !== State.Disconnected && this.state !== State.Invalid) {
            return;
        }

        if(url) {
            this.url = url;
        }
        
        this.state = State.Connecting; // 正在连接
        director.emit(WSConnectingEvent, this.url);

        console.log("开始链接网络_ws :",this.url);
        this.socket =  new WebSocket(this.url);
        this.socket.binaryType = "arraybuffer"; // blob, 二进制; 

        this.socket.onopen = this._onWebSocketOpened.bind(this);
        this.socket.onmessage = this._onRecvDataCmd.bind(this);
        this.socket.onclose = this._onWebSokcetClosed.bind(this);
        this.socket.onerror = this._onWebSocketError.bind(this);
    }

    //微信链接服务
    private _connectToServerWx(url: string = null): void {
        console.log('=====ConnectToServerWx======',this.url,this.state)
        if(this.state !== State.Disconnected && this.state !== State.Invalid) {
            return;
        }

        if(url) {
            this.url = url;
        }
        
        this.state = State.Connecting; // 正在连接
        director.emit(WSConnectingEvent, this.url);

        console.log('=====ConnectToServer=wx======',this.url)
         // 创建WebSocket连接
         this.socket.connectSocket({
            url: this.url, // WebSocket服务器地址
            header: {
                'content-type': 'application/json' // 请求头
            },
            success: ()=> {
              this._onWebSocketOpened();
            },
            fail: (err)=> {
                console.log('WebSocket连接失败：', err);
            }
        });

        // 监听WebSocket连接打开事件
        this.socket.onSocketOpen( ()=> {
            this._onWebSocketOpened();
        });

        // 监听WebSocket接收到服务器的消息事件
        this.socket.onSocketMessage( (res)=> {
            this._onRecvDataCmd(res);
        });

        // 监听WebSocket错误事件
        this.socket.onSocketError( (errMsg)=> {
            console.log('WebSocket发生错误：', errMsg);
            this._onWebSocketError();
        });

        // 监听WebSocket连接关闭事件
        this.socket.onSocketClose( ()=> {
            this._onWebSokcetClosed();
        });
    }

    
    private _sendData(cmdBuf: any): void { // 注意，最好转成arrayBuffer
        if(this.state === State.Connected) {      
            // console.log('=========WsNetMgr=SendData==========',cmdBuf) 
            this.socket.send(cmdBuf);
        }
    }

    //微信发送数据
    private _sendDataWx(cmdBuf: any): void { // 注意，最好转成arrayBuffer
        if (this.state === State.Connected) {
            console.log('=========WsNetMgr=SendData==========',cmdBuf) 
            // 发送数据
            this.socket.sendSocketMessage({
                data: cmdBuf,
                success: () => {
                    console.log('数据发送成功');
                },
                fail: (err) => {
                    console.log('数据发送失败：', err);
                }
            });
        }
    }

    private _loseSocket(callClose: Function = null): void {
        if (this.state === State.Connected) {
            if (this.socket !== null) {
                this.socket.close();
                this.socket = null;
                this.state = State.Invalid;
            }
            // GameTip.inst.showTip('网络连接断开！');
            console.log('============网络连接断开！ ws============',this.state)
            director.emit(WSDisconnectEvent, this.url);
            this.state = State.Disconnected;
            callClose && callClose();
        }else if(this.state === State.Connecting){
            this.state = State.Disconnected;
        }
      
        // console.log('=====CloseSocket ws======');
    }    
    
    public CloseSocket(callClose: Function = null): void {
        if (this.state === State.Connected) {
            if (this.socket !== null) {
                this.socket.close();
                this.socket = null;
                this.state = State.Invalid;
            }
            console.log('============网络连接断开！ ============', this.state)
            director.emit(WSDisconnectEvent, this.url);
            this.state = State.Disconnected;
            callClose && callClose();
        }
      
        // console.log('=====CloseSocket ws======');
    }

    //网络连接成功
    private _onWebSocketOpened(): void {
        this.state = State.Connected; // 连接成功
        console.log('===========网络连接成功！============',this.url);
        globalThis.gameMgr._eventTarget.emit(WSConnectedEvent, this.url);
    }

    //网络连接关闭
    private _onWebSokcetClosed(): void {
        this._loseSocket();
        console.log('============网络连接关闭============',this.state);
    }

    //网络连接出错
    private _onWebSocketError(): void {
        this.CloseSocket();
        console.log('============网络连接错误！============',this.state);
    }

    //收到服务器数据
    private _onRecvDataCmd(event: any): void {
        console.log('============收到服务器数据============');
        var cmdBody = event.data;
        globalThis.gameMgr._eventTarget.emit(WSRecvDataEvent, cmdBody);
    }
}

globalThis.gameMgr.WsMgr = WsMgr; 